package edu.xjtu.jih.signup;

import com.alibaba.fastjson.JSON;
import edu.xjtu.jih.common.Result;
import edu.xjtu.jih.common.Utils;
import edu.xjtu.jih.control.user;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.CharArrayWriter;
import java.io.IOException;
import java.io.Reader;

@WebServlet({
        "/signup",
        "/getUserdetail"
})
public class SignUpAPI extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        SignUpDto dto = null;
        req.setCharacterEncoding("UTF-8");
        SignupService signupService = new SignupService();
        String path=req.getServletPath();
        if("/signup".equals(path)) {
            try {
                Reader reader = req.getReader();
                CharArrayWriter out = new CharArrayWriter();//该输出流将数据输出到一个字符数组中
                boolean exist = true;
                try {
                    char[] charBuff = new char[1024];
                    int len = -1;//每次从输入流实际读取的字符数
                    //System.out.println("1");
                    while ((len = reader.read(charBuff)) != -1) {
                        out.write(charBuff, 0, len);
                    }
                    out.flush();
                    //System.out.println("2");
                    String json = out.toString();

                    dto = JSON.parseObject(json, SignUpDto.class);
                    //System.out.println("3");

                    exist = new SignupService().checkExist(dto);
                    //System.out.println("4");
                } finally {
                    out.close();
                    reader.close();
                }

                if (!exist) {
                    SignupService.addUser(dto);
                    Utils.outResult(resp, Result.success());
                } else {
                    Utils.outResult(resp, Result.fail(Result.ERR_CODE_BUSINESS, "用户名已存在"));
                }
            } catch (Exception e) {
                Utils.outResult(resp, Result.fail(Result.ERR_CODE_SYS, "系统升级中。。。"));
            }
        }
        if("/getUserdetail".equals(path)){

            try {
                SignUpDto signUpDto = Utils.getBeanFromRequest(SignUpDto.class,req);
                user u = signupService.get_userbyid(signUpDto);
                Utils.outJson(resp, Result.success(u));
            }catch (Exception e) {
                Utils.outResult(resp, Result.fail(Result.ERR_CODE_SYS, "系统升级中。。。"));
            }
        }

    }
}
